import { EventNames, useEventCenterOn } from '@/dataTransfer/eventCenter';
import { customeAppId } from '@/src/config';
import { transform2px, transformConfig } from '@/utils/customModule';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { buildPaginationRequest } from '../../utils/product';
import { defaultVisibleEnums } from '../moduleConstants';
import { recommendGoodsStyle } from './constants';
import ModuleProductsThreeColumn from './ModuleProductsThreeColumn';
import ModuleProductsTwoColumn from './ModuleProductsTwoColumn';

const styleConfig = {
  item: ['borderRadius'],
  background: (styleSettingRender) => {
    //  扁平 不用管
    if (styleSettingRender.goodsStyle === recommendGoodsStyle.line) {
      return {
        // backgroundColor: '#fff',
      };
    }

    return {
      // backgroundColor: styleSettingRender.opacity === defaultVisibleEnums.show ? '#fff' : undefined,
    };
  },
  img: [
    (styleSettingRender) => {
      // 不是 扁平 不用管
      if (styleSettingRender.goodsStyle !== recommendGoodsStyle.line) {
        return undefined;
      }

      return {
        borderRadius: transform2px(styleSettingRender.borderRadius),
      };
    },
  ],
};

const components = {
  2: ModuleProductsTwoColumn,
  3: ModuleProductsThreeColumn,
};

const ModuleProducts = ({
  componentCfg: { styleSettingRender,styleSetting, content } = {},
  pageName,
  isLast,
}) => {
  const style = transformConfig(styleSettingRender, styleConfig);

  const [productListInfo, setProductListInfo] = useState({});

  const queryProductList = useMemo(() => {
    if (!content?.goodsSelectInfo) {
      return () => {
        return {};
      };
    }

    return buildPaginationRequest({
      type: 'productList/fetchAppProductInfo',

      payload: {
        appid: customeAppId,
        page: 1,
        pageSize: 10,
        ...content?.goodsSelectInfo,
      },

      isLast,
    });
  }, [content?.goodsSelectInfo]);

  const getNext = useCallback(() => {
    return queryProductList().then((v) => {
      setProductListInfo(v);
    });
  }, [queryProductList]);

  // 首次获取
  useEffect(() => {
    getNext();
  }, [getNext]);

  // 滚动到底部监听
  useEventCenterOn(
    EventNames.ModuleScrollToLower,
    ({ event, pageName: inputPageName, when }) => {
      // 不是同一个页面
      if (inputPageName !== pageName) {
        return;
      }

      console.log('debug for scrollToLower', { event, when });

      getNext();
    },
    [pageName],
  );

  const params = {
    content,
    styleSettingRender,
    styleSetting,
    style,
    productList: productListInfo?.list,
    isFinished: productListInfo?.isFinished,
    isShowLoading: isLast,
  };

  const CustomTag = components[styleSettingRender.style];

  if (!CustomTag) {
    return null;
  }

  return <CustomTag {...params} />;
};

export default ModuleProducts;
